from common.flask_package import *
from model.vip import *
from model.car_info import *
from model.order import *
from model.log import *
from common.my_msg import *
from common.my_fun import *
from datetime import datetime,timedelta
import json

bp_vip = Blueprint('vip', __name__, url_prefix='/vip')
'''
功能：开通vip
用途：前台客户端开通vip
限制:开通了一个卡后不能再开其它卡并且不能取消，需要等待过期后才能继续开通
解释:接收车牌号、月卡、年卡，根据车牌号查询该车牌号是否有开通vip，如果为空说明没开通任何卡，则继续判断当vip_month_card不为空时说名用户需要开
月卡将vip_month_card字段赋值为True表示开通,vip_year_card赋值为False表示未开通，然后保存对应的信息,年卡开通的时间置空，相反年卡也是对应的
操。当查询到该车牌有开通vip记录时（存在记录，可能vip在生效可能都已经过期等），未过期时判断当月卡或年卡中开通了其中一个将警告用户不可继续开通，
当月卡和年卡都过期(False)时，则会重复判断用户开通的是月卡和年卡
'''
#-------------------------开通vip--------------------------------
# @bp_vip.route('/open_vip', methods=['POST'])
# def vip_open_vip():
#     if request.method=='POST':
#         car_number = request.json.get('car_number')
#         vipmoney = request.json.get('vipmoney') #获取前端的金额
#         vip_month_card = request.json.get('vip_month_card') #月卡金额，开通哪个就传递，不开通传递空值
#         vip_year_card = request.json.get('vip_year_card') #年卡金额，开通哪个就传递，不开通传递空值
#         opentime = datetime.now()
#         month_card_money=300 #定义月卡为300
#         year_card_money=3000#定义年卡为300
#         query = Vip.query_car_number_vip(car_number)
#         order_number,time = order_num()  # 获取订单编号以及订单创建时间
#         data = {
#             'code': state_error(),
#             'msg': '操作失败'
#         }
#         if query is None:
#             if vip_month_card:
#                 if int(vipmoney)==month_card_money:
#                     vip_month_card = 'True'
#                     vip_year_card = 'False'
#                     result = Vip.add_vip_info(car_number, vip_month_card, opentime, vip_year_card, None)
#                     if result == 0:
#                         Order.add_order(car_number, order_number, '开通月卡', time, month_card_money)  # 创建订单
#                         data = {
#                             'code': state_ok(),
#                             'msg': '月卡开通成功'
#                         }
#                     else:
#                         data = {
#                             'code': state_error(),
#                             'msg': '月卡开通失败'
#                         }
#                 else:
#                     data = {
#                         'code': state_warn(),
#                         'msg': '请支付正确金额'
#                     }
#             elif vip_year_card:
#                 if int(vipmoney) == year_card_money:
#                     vip_month_card = 'False'
#                     vip_year_card = 'True'
#                     result = Vip.add_vip_info(car_number, vip_month_card, None, vip_year_card, opentime)
#                     if result == 0:
#                         Order.add_order(car_number, order_number, '开通年卡', time,year_card_money)  # 创建订单
#                         data = {
#                             'code': state_ok(),
#                             'msg': '年卡开通成功'
#                         }
#                     else:
#                         data['msg'] = '年卡开通失败'
#                 else:
#                     data = {
#                         'code': state_warn(),
#                         'msg': '请支付正确金额'
#                     }
#         else:
#             if query.vip_month_card=='True' or query.vip_year_card=='True':
#                 data['msg'] = '已经开卡不能再开通'
#                 data['code'] = state_warn()
#             else:
#                 if vip_month_card:
#                     if int(vipmoney) == month_card_money:
#                         vip_month_card = 'True'
#                         result = Vip.modify_is_open_card(car_number, vip_month_card, None)
#                         if result == 4:
#                             Order.add_order(car_number, order_number, '开通月卡', time, month_card_money)  # 创建订单
#                             data = {
#                                 'code': state_ok(),
#                                 'msg': '月卡开通成功'
#                             }
#                         else:
#                             data = {
#                                 'code': state_error(),
#                                 'msg': '月卡开通失败'
#                             }
#                     else:
#                         data = {
#                             'code': state_warn(),
#                             'msg': '请支付正确金额'
#                         }
#
#                 elif vip_year_card:
#                     if int(vipmoney) == year_card_money:
#                         vip_year_card = 'True'
#                         result = Vip.modify_is_open_card(car_number, None, vip_year_card)
#                         if result == 5:
#                             Order.add_order(car_number, order_number, '开通年卡', time, year_card_money)  # 创建订单
#                             data = {
#                                 'code': state_ok(),
#                                 'msg': '年卡开通成功'
#                             }
#                         else:
#                             data['msg'] = '年卡开通失败'
#                     else:
#                         data = {
#                             'code': state_warn(),
#                             'msg': '请支付正确金额'
#                         }
#     return jsonify(data)




#----------------------- 封装产生订单编号函数-----------------------
# 定义月卡支付金额
def montg_pay():
    money=300
    return money

# 定义年卡支付金额
def year_pay():
    money=3000
    return money

'''
功能：开通月卡
用途：前台客户端开通vip
限制:开通了一个卡后不能再开其它卡并且不能取消，需要等待过期后才能继续开通,这里分(月卡和年卡)
实现思路:接收客户端月卡开通金额和车牌号,如果查询到空说明用户未开通过任何卡,则保存用户开通月卡的信息,继续判断查询到用户的信息不为空
说明用户开通过卡(开通过年卡或卡过期,记录保存着),再判断年卡是否在开通状态,如果卡都过期则开通月卡
'''
@bp_vip.route('/month/open',methods=['POST'])
def vip_month_open():
    if request.method=='POST':
        month_money=request.json.get('month_money') #接收月卡开通的金额
        car_number=request.json.get('car_number') #接收开通月卡的车牌号
        money = montg_pay()  # 月卡金额
        order_number, time = order_num()  # 获取订单编号以及订单创建时间
        opentime = datetime.now()
        query=Vip.query_car_number_vip(car_number) #根据车牌号查询vip信息
        if query is None: #判断为空说明未开通过卡
            if int(month_money)==money:  #判断接收的金额是否匹配
                vip_month_card = 'True'
                vip_year_card = 'False'
                result = Vip.add_vip_info(car_number, vip_month_card, opentime, vip_year_card, None)
                if result == 0: #返回0说明保存成功
                    remarks=f'+{money}'
                    Order.add_order(car_number, order_number, '开通月卡', time, month_money)  # 创建订单
                    Total.add_total(car_number, time, money, remarks) #添加总金额流水
                    data = {
                        'code': state_ok(),
                        'msg': '月卡开通成功'
                    }
                else:
                    data = {
                        'code': state_error(),
                        'msg': '月卡开通失败'
                    }
            else:
                data = {
                    'code': state_warn(),
                    'msg': '金额不匹配'
                }
        else:
            if query.vip_year_card != 'True' and query.vip_month_card != 'True':  # 判断全部卡未开通(过期)
                if int(month_money) == money:  # 判断接收的金额是否匹配
                    relust = Vip.modify_open_month_state(car_number, opentime)
                    if relust == 0:
                        remarks = f'+{money}'
                        Order.add_order(car_number, order_number, '开通月卡', time, month_money)  # 创建订单
                        Total.add_total(car_number, time, money, remarks)  # 添加总金额流水
                        data = {
                            'code': state_ok(),
                            'msg': '月卡开通成功'
                        }
                    else:
                        data = {
                            'code': state_error(),
                            'msg': '月卡开通失败'
                        }

                else:
                    data = {
                        'code': state_warn(),
                        'msg': '金额不匹配'
                    }

            else:
                data = {
                    'code': state_warn(),
                    'msg': '已开过卡,不可继续开通'
                }
    return jsonify(data)

'''
功能：开通年卡
用途：前台客户端开通vip
限制:开通了一个卡后不能再开其它卡并且不能取消，需要等待过期后才能继续开通,这里分(月卡和年卡)
实现思路:接收客户端年卡开通金额和车牌号,如果查询到空说明用户未开通过任何卡,则保存用户开通年卡的信息,继续判断查询到用户的信息不为空
说明用户开通过卡(开通过月卡或卡过期,记录保存着),再判断月卡是否在开通状态,如果卡都过期则开通年卡
'''
@bp_vip.route('/year/open',methods=['POST'])
def vip_year_open():
    if request.method=='POST':
        year_money=request.json.get('year_money') #接收年卡开通的金额
        car_number=request.json.get('car_number') #接收开通年卡的车牌号
        money = year_pay()  # 年卡金额
        order_number, time = order_num()  # 获取订单编号以及订单创建时间
        opentime = datetime.now()
        query=Vip.query_car_number_vip(car_number) #根据车牌号查询vip信息
        if query is None: #判断为空说明未开通过卡
            if int(year_money)==money:  #判断接收的金额是否匹配
                vip_month_card = 'False'
                vip_year_card = 'True'
                result = Vip.add_vip_info(car_number, vip_month_card, None, vip_year_card, opentime)
                if result == 0: #返回0说明保存成功
                    remarks=f'+{money}'
                    Order.add_order(car_number, order_number, '开通年卡', time, year_money)  # 创建订单
                    Total.add_total(car_number, time, money, remarks) #添加总金额流水
                    data = {
                        'code': state_ok(),
                        'msg': '年卡开通成功'
                    }
                else:
                    data = {
                        'code': state_error(),
                        'msg': '年卡开通失败'
                    }
            else:
                data = {
                    'code': state_warn(),
                    'msg': '金额不匹配'
                }
        else:
            if query.vip_year_card != 'True' and query.vip_month_card != 'True':  # 判断全部卡未开通(过期)
                if int(year_money) == money:  # 判断接收的金额是否匹配
                    relust = Vip.modify_open_year_state(car_number, opentime)
                    if relust == 0:
                        remarks = f'+{money}'
                        Order.add_order(car_number, order_number, '开通年卡', time, year_money)  # 创建订单
                        Total.add_total(car_number, time, money, remarks)  # 添加总金额流水
                        data = {
                            'code': state_ok(),
                            'msg': '年卡开通成功'
                        }
                    else:
                        data = {
                            'code': state_error(),
                            'msg': '年卡开通失败'
                        }

                else:
                    data = {
                        'code': state_warn(),
                        'msg': '金额不匹配'
                    }

            else:
                data = {
                    'code': state_warn(),
                    'msg': '已开过卡,不可继续开通'
                }
    return jsonify(data)





def order_num():
    time=datetime.now().strftime("%Y%m%d") #格式20230101
    order_end=str((Order.query_end_order()+1)).zfill(2) #新的订单id，补零
    order_id=time+order_end  #订单编号
    nowtime=datetime.now()
    return order_id,nowtime

#-----------------获取开卡信息---------------------------
@bp_vip.route('/get',methods=['GET'])
def vip_get():
    car_number = request.args.get('car_number')
    page = request.args.get('page', default=1)

    if car_number is not None and car_number !='':
        result = Vip.vip_car_number_search(car_number)
        count = 1
    else:
        result, count = Vip.query_vip_page_all(page)

    vip_list = []
    try:
        for i in result:
            item = {
                'vip_id': i.vip_id,
                'car_number': i.car_number,
                'vip_month_card': i.vip_month_card,
                'vip_open_month_card_time':str(i.vip_open_month_card_time),
                'vip_year_card': i.vip_year_card,
                'vip_open_year_card_time': str(i.vip_open_year_card_time),
            }
            vip_list.append(item)

        data = {
            'code': state_ok(),
            'msg': 'vip信息获取成功',
            'count': count,
            'data': vip_list
        }
    except Exception as e:
        data = {
            'code': state_error(),
            'msg': 'vip信息获取失败',
            'count': 1,
            'data': vip_list
        }
        print(e)
    return Response(json.dumps(data),mimetype='application/json')

'''
功能：判断是否过期修改月卡
用途: 前后台
'''

#-----------------判断是否过期修改月卡------------------------
@bp_vip.route('/modify/vip_month', methods=['POST'])
def vip_modify_vip_month():
    if request.method=='POST':
        endtime=datetime.now() #获取当前时间,也就是结束时间
        query=Vip.query_open_vip_month_all() #返回全部开通月卡的字段
        state = '未有用户开通月卡'
        if query: #不为空
            for i in query:
                #有过期
                if (endtime - i.vip_open_month_card_time).days > 30:
                    Vip.modify_vip_month_state(i.vip_id)
                    state='已将过期vip进行重置'
                else:
                    #没过期
                    state='未发现过期vip'
        data={'code':state_ok(),'msg':'检查完成','state':state}
    return jsonify(data)

'''
功能：判断是否过期修改年卡
用途: 前后台
'''

#------------------判断是否过期修改年卡------------------------
@bp_vip.route('/modify/vip_year', methods=['POST'])
def vip_modify_vip_year():
    if request.method=='POST':
        endtime=datetime.now() #获取当前时间,也就是结束时间
        query=Vip.query_open_vip_year_all() #返回全部开通年卡的字段
        state = '未有用户开通年卡'
        if query: #不为空
            for i in query:
                #有过期
                if (endtime - i.vip_open_year_card_time).days > 1:
                    Vip.modify_vip_year_state(i.vip_id)
                    state='已将过期vip进行重置'
                else:
                    #没过期
                    state='未发现过期vip'
        data={'code':state_ok(),'msg':'检查完成','state':state}
    return jsonify(data)


# ----------后台修改月卡会员状态-------------------------------
@bp_vip.route('/new/month_card', methods=['POST'])
def vip_new_month_card():
    if request.method=='POST':
        vip_id=request.json.get('vip_id')
        relust=Vip.modify_is_month_card(vip_id)
        car_number = Vip.query_vip_id_first(vip_id).car_number
        if relust==0:
            Log.add_log('管理员', f'关闭【{car_number}】月卡')  # 添加操作记录
            data={
                'code':state_ok(),
                'msg':'月卡关闭成功',
                'static': 'False',
            }
        elif relust==1:
            order_number, time = order_num()
            Order.add_order(car_number, order_number, '管理员为用户开通月卡', time, 0)  # 创建订单
            Log.add_log('管理员', f'为【{car_number}】开通月卡')  # 添加操作记录
            data = {
                'code': state_ok(),
                'msg': '月卡开通成功',
                'static': 'True'
            }
        elif relust==2:
            data = {
                'code': state_warn(),
                'msg': '年卡已开通成功,不能再开卡',
                'static': 'False'
            }
        else:
            data = {
                'code': state_error(),
                'msg': '修改失败',
                'static': None
            }
    return jsonify(data)


# ----------后台修改年卡会员状态-------------------------------
@bp_vip.route('/new/year_card', methods=['POST'])
def vip_new_year_card():
    if request.method=='POST':
        vip_id=request.json.get('vip_id')
        relust=Vip.modify_is_year_card(vip_id)
        car_number = Vip.query_vip_id_first(vip_id).car_number
        time=datetime.now()
        if relust==0:
            Log.add_log('管理员', f'关闭【{car_number}】年卡')  # 添加操作记录
            data={
                'code':state_ok(),
                'msg':'年卡关闭成功',
                'static':'False'
            }
        elif relust==1:
            order_number,time=order_num()
            Order.add_order(car_number, order_number, '管理员为用户开通年卡', time, 0)  # 创建订单
            Log.add_log('管理员', f'为【{car_number}】开通年卡')  # 添加操作记录
            data = {
                'code': state_ok(),
                'msg': '年卡开通成功',
                'static':'True'
            }
        elif relust==2:
            data = {
                'code': state_warn(),
                'msg': '月卡已开通成功,不能再开卡',
                'static': 'False'
            }
        else:
            data = {
                'code': state_error(),
                'msg': '修改失败',
                'static':None
            }
    return jsonify(data)

#-----------------------管理员为用户开通会员---------------------------
@bp_vip.route('/admin/add', methods=['POST'])
def vip_admin_add():
    if request.method=='POST':
        car_number = request.json.get('car_number')
        type=request.json.get('type')
        relust=Vip.add_car_number_vip(car_number,type)
        if relust==1:
            order_number, time = order_num()
            Order.add_order(car_number, order_number, f'管理员为{car_number}添加月卡', time, 0)  # 创建订单
            Log.add_log('管理员',f'为【{car_number}】添加月卡') #添加操作记录
            data={
                'code':state_ok(),
                'msg':'月卡开通成功'
            }
        elif relust==2:
            order_number, time = order_num()
            Order.add_order(car_number, order_number, f'管理员为{car_number}添加年卡', time, 0)  # 创建订单
            Log.add_log('管理员', f'为【{car_number}】添加年卡') #添加操作记录
            data = {
                'code': state_ok(),
                'msg': '年卡开通成功'
            }
        elif relust==-1:
            data = {
                'code': state_warn(),
                'msg': '已开通会员'
            }
        else:
            data = {
                'code': state_error(),
                'msg': '开通失败'
            }
    return jsonify(data)






